package ddd.ajava.chapter2.question2;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import ddd.ajava.chapter2.question1.Person;
import ddd.ajava.util.StringUtil;

/**
 * @author lenovo
 * 反射提取Person类属性值步骤如下
 * 1.创建Person实例，并为每个属性赋值
 * 2.获取所有属性，及属性值
 * 3.写入文本文件
 */
public class StoreAttrToTxt {
	private Person person=new Person();
	private StringBuilder sb=new StringBuilder();
	
	public static void main(String[] args) {
		StoreAttrToTxt totxt=new StoreAttrToTxt();
		totxt.setAttr();
		totxt.getAttr();
		totxt.outputToTxt();
	}
	
	/**
	 *  idNo = 5122245566
	 *  name = 张小平
	 *  age = 23
	 *  sex = Male
	 *  isMerried = true 
	 */
	private void setAttr(){
		person.setIdNo("5122245566");
		person.setName("张小平");
		person.setAge(23);
		person.setSex("Male");
		person.setIsMerried(true);
	}
	
	private void getAttr(){
		Class clazz=person.getClass();
		Field[] field=clazz.getDeclaredFields();
		for(Field f:field){
			String fieldName=f.getName();
			String methodName="get"+StringUtil.firstCharToUpper(fieldName);
			sb.append(fieldName+" = ");
			try {
				Method method=clazz.getMethod(methodName);
				Object value=method.invoke(person);
				sb.append(value+"\n");
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void outputToTxt(){
		Class clazz=person.getClass();
		String path=this.getClass().getPackage().getName().replace(".","\\");
		String url=System.getProperty("user.dir")+"\\src\\"+path+"\\"+clazz.getSimpleName()+".txt";
		try {
			FileOutputStream fileOutput=new FileOutputStream(url);
			fileOutput.write(sb.toString().getBytes("UTF-8"));
			fileOutput.flush();
			fileOutput.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
